<script setup lang="ts">
import TableHead from './TableHead.vue'
import ReportPerson from './ReportPerson.vue'
import ContextmenuBox from './ContextmenuBox.vue'

import useAll from './useAll'
import { uuid } from '@/utils'
import { loadProductEnergyConsumption } from '@/api/modules/enterpriseQuarterlyReport'

const calculationKeys = [
  'indexValue',
  'indexValueOne',
  'childValueOne',
  'parentValueOne',
]
const calc = computed(() => {
  const listsValue = lists.value
  const keys = calculationKeys

  // 指标值=子项值÷母项值
  const index = (
    a: number | string,
    b: number | string,
  ) => {
    const n = +(+a / +b).toFixed(2)
    return Number.isFinite(n) ? n : ''
  }
  return keys.reduce((acc, vv) => {
    // 本年度指标是计算而来
    // 上年度是带出来的数据
    acc[vv] = listsValue.map((v) => {
      const vd = v.data
      const child = vd.find(x => x.key === 'childValue')
      const parent = vd.find(x => x.key === 'parentValue')
      const target = vd.find(x => x.key === vv)
      return vv === 'indexValue'
        ? index(
          child ? child.value : '',
          parent ? parent.value : '',
        )
        : target?.value
    })
    return acc
  }, {} as any)
})

const {
  columns,
  title,
  lists,
  informant,
  left,
  top,

  clickCallback,
  loadPrevList,
  onContextmenu,
  delRow,
  prependRow,
  appendRow,
  report,
  saveStage,
  exportFile,
} = useAll(loadProductEnergyConsumption, {
  transfer(
    data: any,
    {
      statementFlattenColumns: flattenColumns,
      readonly,
    },
  ) {
    const keys = calculationKeys
    const _props = flattenColumns.map(v => v.prop)
    return data.map((v: any) => {
      return {
        uuid: uuid(),
        informant: {
          personInCharge: v.personInCharge,
          informer: v.informer,
          telephone: v.telephone,
          fillInDate: v.fillInDate,
        },
        data: _props.map((vv) => {
          if (readonly) {
            return {
              key: vv,
              value: String(v[vv] || ''),
              editable: false,
            }
          }
          let editable = true
          const calculable = vv === 'indexValue'
          if (keys.includes(vv)) {
            editable = false
          }
          return {
            key: vv,
            value: String(v[vv] || ''),
            editable,
            calculable,
          }
        }),
      }
    })
  },
  getCalc(
    row: number,
    prop: string,
    value?: string | number | undefined,
  ) {
    return calc.value[prop]?.[row] || value
  },
  createAEmptyRow({
    statementFlattenColumns: flattenColumns,
    readonly,
  }) {
    return {
      uuid: uuid(),
      data: flattenColumns.map(v => ({
        key: v.prop,
        value: '',
        editable:
          !readonly && !calculationKeys.includes(v.prop),
        calculable: v.prop === 'indexValue',
      })),
    }
  },
})
</script>

<template>
  <div
    ref="statementRef"
    class="width-100 height-100 statement-table position-relative overflow-hidden"
  >
    <slot
      name="title"
      :title="title"
      :report="report"
      :load-prev-list="loadPrevList"
      :save-stage="saveStage"
      :export-file="exportFile"
    >
      <h2 class="table-title">
        {{ title }}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <TableHead
          :columns="columns"
          show-line-number
        />
      </table>
    </div>
    <ElScrollbar
      class="bg-color"
      style="height: calc(100% - 128px)"
      wrap-style="overflow-x: hidden;"
    >
      <table class="report-table">
        <tbody ref="tbody">
          <tr v-for="(item, i) in lists" :key="item.uuid">
            <th class="readonly width-40px line-number">
              {{ i + 1 }}
            </th>
            <td
              v-for="(d, index) in item.data"
              :key="item.uuid + index"
              :class="{
                'is-calculable': d.calculable,
                'readonly': !d.editable,
              }"
            >
              <div v-if="!d.editable" class="span-cell">
                {{
                  d.calculable ? calc[d.key][i] : d.value
                }}
              </div>
              <div v-else class="input-cell">
                <input
                  v-model="d.value"
                  type="text"
                  @click="clickCallback"
                  @contextmenu="
                    evt => onContextmenu(evt, i)
                  "
                >
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="fill-description">
        <ReportPerson v-model="informant" />
        <p>说明：</p>
        <p>
          1．本表甲栏按照附件3《工业企业单位产品能耗指标填报目录》填写。
        </p>
        <p>
          2．国家（地区）限额按照国家或地区能耗限额标准填写，如果没有能耗限额标准可不填写。
        </p>
        <p>
          3．对影响能耗指标变化的主要原因给予说明，字数在100个汉字以内。
        </p>
      </div>
    </ElScrollbar>
    <ContextmenuBox
      :left="left"
      :top="top"
      @del-row="delRow"
      @prepend-row="prependRow"
      @append-row="appendRow"
    />
  </div>
</template>
